package edu.gatech.cs2340.teamrocket.control.networking.node;

import java.io.IOException;
import java.net.ServerSocket;
import edu.gatech.cs2340.teamrocket.control.networking.dialog.ServerDialog;

/**
 * Listens over the port number in Node and opens new Socket connections
 * for the Server class.
 *
 * @author Joe Tacheron
 */
public class PortListeningRunnable implements Runnable {

    private Server server;
    private volatile boolean running;

    public PortListeningRunnable(Server s){
        server = s;
        running = true;
    }

    @Override
    public void run() {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(Node.portNum);

            while (running){
                new ServerDialog(server, serverSocket.accept()).start();
            }

            serverSocket.close();
        }
        catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(-1);
        }
        System.out.println("stop listening");
    }

    /**
     * Stop this runnable.
     */
    public void close(){
        running = false;
    }
}
